PHP 递归函数的应用(二) 文件夹目录遍历

文件夹目录的遍历同样也利用递归去一层一层的遍历文件

以下面这个目录为例的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

//$onlyDir 是否只输出目录
function dirList($dir, $onlyDir = true)
{
$result = array();
$handle = opendir($dir);
if ($handle) {
while (($file = readdir($handle)) !== false) {
if ($file != '.' && $file != '..') {
$cur_path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($cur_path)) {
$result[$file] = dirList($cur_path, $onlyDir);
} else {
if (!$onlyDir) {
$result[] = $file;
}
}
}
}
closedir($handle);
}
return $result;
}

运行dirList('/web/mall/Application/lib', false)
打印数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
array(3) {
["Action"]=>
array(3) {
["Admin"]=>
array(10) {
[0]=>
string(20) "GoodAction.class.php"
[1]=>
string(21) "IndexAction.class.php"
[2]=>
string(21) "LoginAction.class.php"
[3]=>
string(20) "MenuAction.class.php"
[4]=>
string(21) "OrderAction.class.php"
[5]=>
string(22) "PublicAction.class.php"
[6]=>
string(20) "UserAction.class.php"
[7]=>
string(20) "UtilAction.class.php"
[8]=>
string(22) "WechatAction.class.php"
[9]=>
string(22) "WeixinAction.class.php"
}
["Api"]=>
array(1) {
[0]=>
string(19) "ApiAction.class.php"
}
["App"]=>
array(2) {
[0]=>
string(21) "IndexAction.class.php"
[1]=>
string(13) "Sms.class.php"
}
}
[0]=>
string(7) "log.txt"
["Model"]=>
array(2) {
["Admin"]=>
array(1) {
[0]=>
string(20) "OrderModel.class.php"
}
["App"]=>
array(1) {
[0]=>
string(20) "OrderModel.class.php"
}
}
}

可以很清晰的看出一层一层的结构